package com.study.algorithm.niuke.huawei.testquestionsone;

/**
 * 去重和排序
 */
public class SortAndRemoveRedudancy {


    int getRandom(int max, int min) {
        return (int) (Math.random() * (max - min) + min);
    }

    public static void main(String[] args) {
        int size = 100;
        int[] inputArray = new int[size];


        SortAndRemoveRedudancy sort = new SortAndRemoveRedudancy();
        for (int i = 0; i < size; i++) {
            inputArray[i] = sort.getRandom(1000, 1);
        }
        int endIndex = sort.sortAndReturnEndIndex(inputArray);
        for (int currIndex = 0; currIndex <= endIndex; currIndex++) {
            if (currIndex != 0 && currIndex % 10 == 0) {
                System.out.println(inputArray[currIndex]);
                continue;
            }
            System.out.print(inputArray[currIndex] + ":");
        }
    }

    /**
     * @param inputArray
     * @return 返回排序和已经去重之后的结束索引位置
     */
    private int sortAndReturnEndIndex(int[] inputArray) {

        int currEndIndex = 0;
        int gap = 1;
        for (int index = 1; index < inputArray.length; index++) {
            int currVal = inputArray[index];
            int insertIndex = searchInsertIndex(inputArray, currEndIndex, currVal);
            if (insertIndex == -1) {
                if (currVal < inputArray[currEndIndex]) {
                    currEndIndex++;
                    inputArray[currEndIndex] = currVal;
                }
                continue;
            }
            moveElementToNextIndexWithGap(inputArray, insertIndex, currEndIndex, gap);
            currEndIndex++;
            inputArray[insertIndex] = currVal;
        }

        return currEndIndex;

    }

    /**
     * @param inputArray
     * @param endIndex
     * @return 返回-1代表无须插入，返回其他值就为需要插入位置
     */
    private int searchInsertIndex(int[] inputArray, int endIndex, int insertVal) {
        int notNeedInsert = -1;
        for (int currIndex = 0; currIndex <= endIndex; currIndex++) {
            int currVal = inputArray[currIndex];
            if (currVal < insertVal) {
                continue;
            }
            if (currVal == insertVal) {
                return notNeedInsert;
            }
            return currIndex;
        }
        return notNeedInsert;
    }

    private void moveElementToNextIndexWithGap(int[] inputArray, int startIndex, int endIndex, int gap) {
//        if (startIndex > endIndex || endIndex + gap >= inputArray.length) {
//            throw new ArrayIndexOutOfBoundsException("数组越界");
//        }
        for (int currIndex = endIndex; currIndex >= startIndex; currIndex -= gap) {
            inputArray[currIndex + gap] = inputArray[currIndex];
        }

    }

}
